import requests
import json
from functools import wraps
import time

class CodingManager:  
    def __init__(self, access_token, coding_url):  
        self.access_token = access_token  
        self.gitlab_url = coding_url  
        self.headers = {  
            'Accept': 'application/json',
            'Authorization': f'token {access_token}',
            'Content-Type': 'application/json'  
        }
    
    def response_management(func):  
        @wraps(func)  
        def wrapper(self, *args, **kwargs):  
            start_time = time.time()  # 记录开始时间  
            response = func(self, *args, **kwargs)  
            end_time = time.time()  # 记录结束时间  
            execution_time = end_time - start_time  # 计算执行时间  
            
            if response.status_code in (200, 201):  
                print(f'访问成功: {func.__name__} 方法！执行时间: {execution_time:.2f} 秒')  
                return response.json()  
            else:  
                print(f'访问失败: {func.__name__} 方法！执行时间: {execution_time:.2f} 秒')  
                print('状态码:', response.status_code)  
                print('响应内容:', response.json())  
                return None   
        return wrapper 

    @response_management
    def get_project_list(self, project_name="", page_size="20"):  
        """
        查询所有项目
        projectname: [非必填]
        """  
        url = f'{self.gitlab_url}/open-api/DescribeCodingProjects?Action=DescribeCodingProjects'  
        
        post_data = {
            "PageNumber": "1",
            "PageSize": page_size,
            "ProjectName": project_name
        }
        
        response = requests.post(url, headers=self.headers, data=json.dumps(post_data)) 
        
        return response
    
    @response_management
    def get_project_git_repository(self, project_id, page_size="1"):  
        """
        查询项目下所有仓库信息
        project_id: 项目id
        """  
        url = f'{self.gitlab_url}/open-api/DescribeProjectDepotInfoList?Action=DescribeProjectDepotInfoList'  
        
        post_data = {
            "PageNumber": "1",
            "PageSize": page_size,
            "ProjectId": project_id
            }
        
        response = requests.post(url, headers=self.headers, data=json.dumps(post_data)) 
        
        return response

    
